package main

import (
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/stream_grpc_test/proto"
	"google.golang.org/grpc"
	"net"
	"sync"
	"time"
)

const PORT string = ":8081"

type Server struct {
	proto.UnimplementedGreeterServer
}

func (s *Server) GetStream(req *proto.StreamReqData, res proto.Greeter_GetStreamServer) error {
	i := 0
	for {
		i++
		_ = res.Send(&proto.StreamRespData{
			Data: fmt.Sprintf("%v", time.Now().UnixMilli()),
		})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}
func (s *Server) PutStream(cliStr proto.Greeter_PutStreamServer) error {
	for {
		a, err := cliStr.Recv()
		if err != nil {
			fmt.Println(err)
			return err
			break
		}
		fmt.Println(a)
	}
	return nil
}
func (s *Server) AllStream(allStr proto.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			fmt.Println("收到客户端发送的消息：", data.Data, data.G, data.AddTime)
		}
	}()
	go func() {
		defer wg.Done()
		for {
			allStr.Send(&proto.StreamRespData{
				Data: "服务器收到了客户端的消息",
				Mp: map[string]string{
					"map.data": "resp-server",
					"time":     "20250207",
				},
			})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	return nil
}

func main() {
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		panic("failed to listen: " + err.Error())
	}
	s := grpc.NewServer()
	proto.RegisterGreeterServer(s, &Server{})
	s.Serve(lis)
}
